import PropTypes from 'prop-types';
import { ProColumnType, ProField, ProFormInstance, ProFormItem } from '@ant-design/pro-components';
import {
  ProCard,
  ProForm,
  ProFormDependency,
  ProFormDigit,
  ProFormGroup,
  ProFormList,
  ProFormRadio,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
  useDebounceFn,
  FormListActionType,
} from '@ant-design/pro-components';
import { Button, message, Row, Col, Tabs, Tooltip, Space } from 'antd';
import React, { useContext } from 'react';
import { useRef, useState } from 'react';
import { request } from 'umi';
import lodash from 'lodash';
import { ApiInfo, ApiType, ProTableContexteValue, ProTableInfo, TableColumn, TablePagination } from '../../ProTableDynamic/utils/types';
import { initConfig, renderColumn } from '../../ProTableDynamic/config';
import { configSettingUI } from '../configSettingUI';
import { dataSource } from '../../ProTableDynamic/utils/dataSource';
import generateUtil, { generateDealString, restoreFromLocalStorage } from '../../../utils/backRestore';
import { OperationDynamic } from '../../ProTableDynamic/subComps/OperationDynamic/index';
import { ProTableContext } from '@/components/Context/ProTableContext';
import { SchemeItem, SchemeItemInfo, valueTypeArray } from '../../../utils/types';
import { dealApiSelectList } from '@/utils/dataDeal';
import { ArrowDownOutlined, ArrowUpOutlined, VerticalAlignBottomOutlined, VerticalAlignTopOutlined } from '@ant-design/icons';
import './setting.less';
import storage from '../../../utils/storage';

let columnsStr = ''; // 表格列中会有函数，无法序列化，用此字符串存储无法被序列化的columns数据
const ProTableDynamicSettings = (props: any) => {
  ///开始删除
  // 全局数据源
  const proTableContexteValue: ProTableContexteValue = useContext<ProTableContexteValue>(ProTableContext); // 获取公共数据
  ///结束删除

  const baseFormRef = useRef<ProFormInstance>(); // 基础配置表单
  const columnFormRef = useRef<ProFormInstance>(); // 列配置表单
  const columnFormListRef = useRef<FormListActionType<any>>(); // 列List表单
  const dataSourceFormRef = useRef<ProFormInstance>(); // 数据源表单

  const generateFormRef = useRef<ProFormInstance>(); // 代码生成表单
  const [config, setConfig] = useState<ProTableInfo>(initConfig(() => {}));
  const setConfigContext = (proTableInfo: ProTableInfo) => {
    setConfig(proTableInfo);
    proTableContexteValue.setTableInfo(proTableInfo);
  };
  // 去抖配置
  const updateConfig = useDebounceFn(async (state) => {
    const newConfig = {};
    lodash.merge(newConfig, config);
    lodash.merge(newConfig, state);
    console.debug('setting更新表单', state, config, newConfig);
    setConfigContext({ ...newConfig });
  }, 20);
  //# region 本地方案缓存配置
  const localStorageFormRef = useRef<ProFormInstance>(); // 代码生成表单
  const updateLocalStorageConfig = useDebounceFn(async (state) => {}, 20);
  // 全部重新加载
  const reloadSchemeInfo = () => {
    const schemeItemInfo: SchemeItemInfo = storage.getProTableInfo();
    localStorageFormRef.current?.setFieldsValue(schemeItemInfo);
  };
  // 使用方案
  const loadSchemeInfo = (index: number) => {
    const schemeItemInfo: SchemeItemInfo = storage.getProTableInfo();
    const schemeItem: SchemeItem = schemeItemInfo.schemeList[index];
    let newProTableContexteValue: ProTableContexteValue = JSON.parse(schemeItem.data);
    newProTableContexteValue = restoreFromLocalStorage(newProTableContexteValue, props.onSettingEvent);
    setConfigContext(newProTableContexteValue.tableInfo);
    proTableContexteValue.setFormInfo(newProTableContexteValue.formInfo); // 额外设置表单信息
  };
  // 删除
  const removeSchemeInfo = (index: number) => {
    const schemeItemInfo: SchemeItemInfo = storage.getProTableInfo();
    const schemeItem: SchemeItem = schemeItemInfo.schemeList[index];
    storage.removeProTableInfo(schemeItem.key);
    reloadSchemeInfo();
  };
  // 保存当前方案
  const saveSchemeInfo = () => {
    const proTableContexteValueString = JSON.stringify(proTableContexteValue);
    storage.saveProTableInfo(proTableContexteValueString);
    reloadSchemeInfo();
  };

  React.useEffect(() => {
    // console.debug('配置的config发生变化', config);
    props.dynamicSetConfig(config);
  }, [config]);
  //# endregion

  //#region 数据源表单配置

  const exeTableListDataSource = async (list: ApiInfo) => {
    const apiType = 'list';
    // list.parameter[config.dataSource.paginationInfo.currentField] = current;
    // list.parameter[config.dataSource.paginationInfo.pageSizeField] = pageSize;

    const tablePagination: TablePagination = await dataSource(apiType, list, '');
    if (!tablePagination) return;
    let tableColumn: any[] = dealApiSelectList(tablePagination.dataList); // 处理生成表格的列信息
    const tableColumnLength: number = tableColumn.length;
    let maxColumnOrder = 1;
    if (tableColumnLength > 0) maxColumnOrder = tableColumn[tableColumnLength - 1].columnOrder; // 获取最大的排序值赋给操作栏
    // #region 操作栏
    const operationColumn: any = {
      title: '操作',
      dataIndex: 'table-operation', // 防止后端字段重名
      valueType: 'option',
      columnOrder: maxColumnOrder + 1,
      render: renderColumn(props.onSettingEvent),
    };

    tableColumn.push(operationColumn);
    //#endregion

    // setting
    config.tableConfig.columns = tableColumn;
    config.dataSource.apiList[apiType].data = [tablePagination.dataList, tablePagination.total];
    // console.debug('setting的config更新', config);
    setConfigContext({ ...config });

    baseFormRef.current?.setFieldsValue({ ...config }); // 需要更新基础配置表单
    columnFormRef.current?.setFieldsValue({ ...config }); // 需要更新列表单

    console.debug('exeTableListDataSource', config.tableConfig);

    props.onEventTabelType('eventReloadTable');
  };

  const exetDataSource = (apiType: ApiType) => {
    // console.debug('exetDataSource', apiType, config);
    switch (apiType) {
      case 'list':
        exeTableListDataSource(config.dataSource.apiList[apiType]);
        break;
      default:
        message.error('数据源类型错误' + apiType);
        return;
    }
  };
  //#endregion

  //#region 代码生成表单配置
  const fillGenerate = () => {
    // 一键填写
    generateFormRef?.current?.setFieldsValue({
      name: 'ComponentName',
      // type: 'CommonTable',
      // templatePath: 'F:\\zhaotong\\Git\\ant-design-generate\\front\\src\\components\\ProTableDynamic',
      // generatePath: 'F:\\zhaotong\\Git\\ant-design-generate\\front\\src\\components\\Generate',
      templatePath: 'D:\\ZT\\Git\\ant-design-generate\\front\\src\\components\\ProTableDynamic',
      generatePath: 'D:\\ZT\\Git\\ant-design-generate\\front\\src\\components\\Generate',
      previewUrl: 'http://localhost:8000/generate',
      // initData: JSON.stringify({ ...config }),
    });
  };
  // 生成
  const generate = async (values: any) => {
    const url = '/api/generate';
    let initData = { ...config };
    const newInitDataStr = generateUtil(initData, generateDealString('tableOperation'));
    const formInfo = proTableContexteValue.formInfo;
    delete formInfo?.currentTableRecord?.reactNode;
    await request(url, {
      method: 'post',
      data: {
        ...values,
        tableInfo: newInitDataStr,
        formInfo: JSON.stringify(formInfo),
      },
    })
      .then(function (response) {
        if (response && response.successed) {
          message.success('请求成功');
        } else {
          console.error('生成出错啦', response);
          message.error('生成出错啦');
        }
      })
      .catch(function (error) {
        console.error('生成出错啦', error);
        message.error('生成出错啦', error);
      });
  };
  //#endregion

  // 设置表格行主键
  const setRowKey = (dataIndex: string) => {
    const newConfig = {};
    lodash.merge(newConfig, config);
    lodash.merge(newConfig, { dataSource: { keyInfo: { key: dataIndex } } });
    lodash.merge(newConfig, { tableConfig: { rowKey: dataIndex } });
    setConfigContext(newConfig);

    dataSourceFormRef.current?.setFieldsValue(newConfig);
  };
  /** 调整表格Columns顺序,columnOrder都是从1开始步长为1的递增序列
   * @param index 当前操作的column 索引 从0开始
   */
  const adjustColumnOrder = (direction: 'up' | 'upTop' | 'down' | 'downBottom', index: number) => {
    let columns = [...config.tableConfig.columns];
    const currentColumnsOrder = columns[index].columnOrder;

    let minColumn: TableColumn = {};
    let maxColumn: TableColumn = {};

    if (columns.length > 0) {
      minColumn = columns[0];
      maxColumn = columns[columns.length - 1];
    }

    if (direction === 'up') {
      if (minColumn.columnOrder === currentColumnsOrder) {
        message.info('已经在最上啦');
        return;
      }
      const tempColumnOrder = columns[index - 1].columnOrder;
      columns[index - 1].columnOrder = columns[index].columnOrder;
      columns[index].columnOrder = tempColumnOrder;
    }
    if (direction === 'upTop') {
      if (minColumn.columnOrder === currentColumnsOrder) {
        message.info('已经在最上啦');
        return;
      }

      columns[index].columnOrder = minColumn.columnOrder;
      // 当前操作列之前的向后排一个,将当前操作的列放到顶部
      for (let i = 0; i < index; i++) {
        const column = columns[i];
        column.columnOrder = column.columnOrder + 1;
      }
    }
    if (direction === 'down') {
      if (maxColumn.columnOrder === currentColumnsOrder) {
        message.info('已经在最下啦');
        return;
      }
      const tempColumnOrder = columns[index + 1].columnOrder;
      columns[index + 1].columnOrder = columns[index].columnOrder;
      columns[index].columnOrder = tempColumnOrder;
    }
    if (direction === 'downBottom') {
      if (maxColumn.columnOrder === currentColumnsOrder) {
        message.info('已经在最下啦');
        return;
      }

      columns[index].columnOrder = maxColumn.columnOrder;
      // 当前操作列之后的向后前一个,将当前操作的列放到底部
      for (let i = index + 1; i < columns.length; i++) {
        const column = columns[i];
        column.columnOrder = column.columnOrder - 1;
      }
    }
    //升序
    columns = columns.sort((a: TableColumn, b: TableColumn) => {
      return a.columnOrder - b.columnOrder;
    });
    config.tableConfig.columns = columns;
    setConfigContext({ ...config });

    columnFormRef.current?.setFieldsValue({ ...config }); // 更新列表单
    // console.debug('adjustColumnOrder', config);
  };

  React.useEffect(() => {
    baseFormRef.current?.setFieldsValue(config);
    columnFormRef.current?.setFieldsValue(config);
    dataSourceFormRef.current?.setFieldsValue(config);
    fillGenerate();
    reloadSchemeInfo();
    exetDataSource('list'); // 初始化执行一次
  }, []);

  console.debug('ProTableDynamicSettings setting', config);
  const columnLayout12: any = { labelAlign: 'left', labelCol: { span: 7 }, wrapperCol: { span: 16 } };
  const columnLayout8: any = { labelAlign: 'left', labelCol: { span: 14 }, wrapperCol: { span: 9 } };
  const dataSourceLayout24: any = { labelAlign: 'left', labelCol: { span: 6 }, wrapperCol: { span: 18 } };
  return (
    <>
      <Tabs
        defaultActiveKey="tab1"
        style={{
          height: '100%',
          overflow: 'auto',
        }}
        tabBarStyle={{ paddingLeft: '10px', paddingRight: '10px', margin: '0' }}
        animated={true}
        items={[
          {
            label: '基本配置',
            key: 'base',
            forceRender: true,
            children: (
              <div className="tabChildren">
                <ProForm
                  layout="horizontal"
                  labelAlign="left"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 16 }}
                  size={configSettingUI.size}
                  formRef={baseFormRef}
                  submitter={false}
                  colon={false}
                  onValuesChange={(_, values) => updateConfig.run(values)}
                >
                  {/* <ProForm.Group title="事件配置" collapsible direction="horizontal" labelLayout="twoLine"></ProForm.Group> */}
                  <ProForm.Group title="表格配置" collapsible direction="horizontal" labelLayout="twoLine">
                    <ProFormSwitch label="边框" tooltip="bordered" name={['tableConfig', 'bordered']} />
                    {/* <ProFormSwitch label="加载中" tooltip="loading" name={['showLoading']} /> */}
                    <ProFormRadio.Group
                      tooltip={`size="middle"`}
                      radioType="button"
                      label="尺寸"
                      options={[
                        {
                          label: '小',
                          value: 'small',
                        },
                        {
                          label: '中',
                          value: 'middle',
                        },
                        {
                          label: '大',
                          value: 'default',
                        },
                      ]}
                      name={['tableConfig', 'size']}
                    />
                    <ProFormSwitch label="开启展开" tooltip="expandable" name={['showExpandable']} />
                    <ProFormSwitch label="行选择" tooltip="rowSelection" name={['tableConfig', 'rowSelection']} />

                    {/* <ProFormSwitch label="横向滚动" tooltip="openXScroll" name="openXScroll" />
                    <ProFormDependency name={['openXScroll']}>
                      {({ openXScroll }) => {
                        if (!openXScroll) {
                          return null;
                        }
                        return (
                          <>
                            <ProFormDigit label="表格宽度" tooltip={`scroll="${config.scroll.x}"`} name={['scroll', 'x']} />
                          </>
                        );
                      }}
                    </ProFormDependency>
                    <ProFormSwitch label="纵向滚动" tooltip="openYScroll" name="openYScroll" />
                    <ProFormDependency name={['openYScroll']}>
                      {({ openYScroll }) => {
                        if (!openYScroll) {
                          return null;
                        }
                        return (
                          <>
                            <ProFormDigit label="表格高度" tooltip={`scroll="${config.scroll.y}"`} name={['scroll', 'y']} />
                          </>
                        );
                      }}
                    </ProFormDependency> */}
                    <ProFormSwitch label="开启滚动" tooltip="openScroll" name={['openScroll']} />
                    <ProFormDependency name={['openScroll']}>
                      {({ openScroll }) => {
                        // console.log(value);
                        if (!openScroll) {
                          return null;
                        }
                        return (
                          <>
                            <ProFormDigit label="表格宽度" tooltip={`scroll.x:"${config.tableConfig.scroll.x}"`} name={['tableConfig', 'scroll', 'x']} />
                            <ProFormDigit label="表格高度" tooltip={`scroll.y:"${config.tableConfig.scroll.y}"`} name={['tableConfig', 'scroll', 'y']} />
                          </>
                        );
                      }}
                    </ProFormDependency>

                    <ProFormRadio.Group
                      radioType="button"
                      name={['tableConfig', 'tableLayout']}
                      tooltip={`tableLayout:"${config.tableLayout}"`}
                      options={[
                        {
                          label: 'auto',
                          value: 'auto',
                        },
                        {
                          label: 'fixed',
                          value: 'fixed',
                        },
                      ]}
                      label="表格布局"
                    />
                    <ProFormSwitch label="显示左侧工具栏" tooltip="showToolbar" name={['showToolbar']} />
                    <ProFormText label="标题" name={['tableConfig', 'headerTitle']} tooltip="headerTitle={false}" />
                    <ProFormText label="标题tooltip" name={['tableConfig', 'tooltip']} tooltip="tooltip={false}" />
                    <ProFormSwitch label="表格footer" tooltip="showFooter" name={['showFooter']} />
                    <ProFormDependency name={['showFooter']}>
                      {({ showFooter }) => {
                        if (!showFooter) {
                          return null;
                        }
                        return <ProFormText label="表格Footer" tooltip="footerTitle={false}" name={['tableConfig', 'footer']} />;
                      }}
                    </ProFormDependency>
                  </ProForm.Group>
                  <ProForm.Group
                    collapsible
                    direction="horizontal"
                    labelLayout="twoLine"
                    tooltip="showToolBarRender={false}"
                    title="显示工具栏"
                    extra={<ProFormSwitch noStyle name="showToolBarRender" />}
                  >
                    <ProFormSwitch label="显示表头" tooltip="showHeader" name={['tableConfig', 'showHeader']} />
                    <ProFormSwitch label="显示选项" tooltip="showOptions" name="showOptions" />
                    <ProFormDependency name={['showOptions']}>
                      {({ showOptions }) => {
                        // console.log('----------', showOptions);
                        if (!showOptions) {
                          return <></>;
                        }
                        return (
                          <>
                            {/* <ProFormSwitch label="Icon 显示" name={['tableConfig', 'options', 'show']} tooltip="options={false}" /> */}
                            <ProFormSwitch label="刷新" name={['tableConfig', 'options', 'reload']} tooltip="options={{ reload:false }}" />
                            <ProFormSwitch label="密度" name={['tableConfig', 'options', 'density']} tooltip="options={{ density:false }}" />
                            <ProFormSwitch label="搜索" name={['tableConfig', 'options', 'search']} tooltip="options={{ search:'keyWords' }}" />
                            <ProFormSwitch label="全屏" name={['tableConfig', 'options', 'fullScreen']} tooltip="options={{ fullScreen:false }}" />
                            <ProFormSwitch label="列配置" name={['tableConfig', 'options', 'setting']} tooltip="options={{ setting:false }}" />
                          </>
                        );
                      }}
                    </ProFormDependency>
                  </ProForm.Group>
                  <ProForm.Group
                    title="查询表单"
                    collapsible
                    tooltip="search={false}"
                    direction="horizontal"
                    labelLayout="twoLine"
                    extra={<ProFormSwitch noStyle name={['showSearch']} />}
                  >
                    <ProFormText label="查询按钮文案" tooltip={`search={{searchText:"查询"}}`} name={['tableConfig', 'search', 'searchText']} />
                    <ProFormText label="重置按钮文案" tooltip={`search={{resetText:"重置"}}`} name={['tableConfig', 'search', 'resetText']} />
                    <ProFormSwitch label="折叠按钮" tooltip={`search={{collapseRender:false}}`} name={['tableConfig', 'search', 'collapseRender']} />
                    <ProFormSwitch label="折叠表单" tooltip={`search={{collapsed:false}}`} name={['tableConfig', 'search', 'collapsed']} />
                    <ProFormSelect
                      tooltip={`search={{span:8}}`}
                      options={[
                        {
                          label: '24',
                          value: 24,
                        },
                        {
                          label: '12',
                          value: 12,
                        },
                        {
                          label: '8',
                          value: 8,
                        },
                        {
                          label: '6',
                          value: 6,
                        },
                      ]}
                      label="表单栅格"
                      name={['tableConfig', 'search', 'span']}
                    />
                    <ProFormRadio.Group
                      radioType="button"
                      tooltip={`search={{layout:"${config.search?.layout}"}}`}
                      options={[
                        {
                          label: '垂直',
                          value: 'vertical',
                        },
                        {
                          label: '水平',
                          value: 'horizontal',
                        },
                      ]}
                      label="表单布局"
                      name={['tableConfig', 'search', 'layout']}
                    />
                    <ProFormRadio.Group
                      radioType="button"
                      tooltip={`search={{filterType:"light"}}`}
                      options={[
                        {
                          label: '默认',
                          value: 'query',
                        },
                        {
                          label: '轻量',
                          value: 'light',
                        },
                      ]}
                      label="表单类型"
                      name={['tableConfig', 'search', 'filterType']}
                    />
                  </ProForm.Group>
                  <ProForm.Group
                    title="分页器"
                    collapsible
                    tooltip="pagination={}"
                    direction="horizontal"
                    labelLayout="twoLine"
                    extra={<ProFormSwitch noStyle name={['showPagination']} />}
                  >
                    <ProFormRadio.Group
                      tooltip={`pagination={size:"middle"}`}
                      radioType="button"
                      label="尺寸"
                      options={[
                        {
                          label: '默认',
                          value: 'default',
                        },
                        {
                          label: '小',
                          value: 'small',
                        },
                      ]}
                      name={['tableConfig', 'pagination', 'size']}
                    />
                    {/* <ProFormRadio.Group
                      tooltip={`pagination={size:"middle"}`}
                      radioType="button"
                      label="位置"
                      options={[]}
                      name={['pagination', 'position']}
                    /> */}
                    <ProFormDigit label="页码" tooltip={`pagination={{ current:10 }}`} name={['tableConfig', 'pagination', 'current']} />
                    <ProFormDigit label="每页数量" tooltip={`pagination={{ pageSize:10 }}`} name={['tableConfig', 'pagination', 'pageSize']} />
                    {/* <ProFormDigit label="数据总数" tooltip={`pagination={{ total:100 }}`} name={['tableConfig', 'pagination', 'total']} /> */}
                    <ProFormSwitch label="分页切换器" tooltip={`pagination={{ showSizeChanger:true}}`} name={['tableConfig', 'pagination', 'showSizeChanger']} />
                  </ProForm.Group>
                </ProForm>
              </div>
            ),
          },
          {
            label: '列配置',
            key: 'columns',
            forceRender: true,
            children: (
              <div className="tabChildren">
                <ProForm
                  layout="inline"
                  size={configSettingUI.size}
                  formRef={columnFormRef}
                  submitter={false}
                  colon={false}
                  onValuesChange={(_, values) => updateConfig.run(values)}
                >
                  <ProFormList
                    name={['tableConfig', 'columns']}
                    style={{ width: '100%' }}
                    actionRef={columnFormListRef}
                    itemRender={({ listDom, action }) => {
                      return (
                        <ProCard
                          className="datasource-form-list-card"
                          bordered
                          style={{
                            marginBlockEnd: 8,
                            position: 'relative',
                            padding: '10px 0px',
                          }}
                          bodyStyle={{
                            width: '100%',
                            padding: 8,
                            paddingBlockStart: 16,
                          }}
                        >
                          <div
                            style={{
                              position: 'absolute',
                              top: -4,
                              right: 2,
                              display: 'flex',
                              cursor: 'pointer',
                            }}
                          >
                            {action}
                          </div>
                          {listDom}
                        </ProCard>
                      );
                    }}
                  >
                    {(
                      // 当前行的基本信息 {name: number; key: number}
                      meta,
                      // 当前的行号
                      index,
                      /**
                       * action
                       * @name 用于操作行的一些快捷方法
                       * @example 给第二行增加数据 action.add?.({},1);
                       * @example 删除第二行 action.remove?.(1);
                       * @example 从 1 移到 2: action.move?.(2,1);
                       * @example 获取当前行的数据: action.getCurrentRowData() -> {id:"xxx",name:'123',age:18}
                       * @example 设置当前行的数据: {id:"123",name:'123'} -> action.setCurrentRowData({name:'xxx'}) -> {id:"123",name:'xxx'}
                       * @example 清空当前行的数据：{id:"123",name:'123'} -> action.setCurrentRowData({name:undefined}) -> {id:"123"}
                       */
                      action,
                      // 总行数
                      count,
                    ) => {
                      return (
                        <div key={'row_' + index} className="column-item">
                          <Row style={{ position: 'absolute', top: '5px', right: '45px' }}>
                            <Tooltip placement="top" title="置顶">
                              <VerticalAlignTopOutlined
                                onClick={(event) => {
                                  adjustColumnOrder('upTop', index);
                                }}
                              />
                            </Tooltip>
                            <Tooltip placement="top" title="置底">
                              <VerticalAlignBottomOutlined
                                style={{ marginLeft: '8px' }}
                                onClick={(event) => {
                                  adjustColumnOrder('downBottom', index);
                                }}
                              />
                            </Tooltip>
                            <Tooltip placement="top" title="上移一格">
                              <ArrowUpOutlined
                                style={{ marginLeft: '8px' }}
                                onClick={(event) => {
                                  adjustColumnOrder('up', index);
                                }}
                              />
                            </Tooltip>
                            <Tooltip placement="top" title="下移一格">
                              <ArrowDownOutlined
                                style={{ marginLeft: '8px' }}
                                onClick={(event) => {
                                  adjustColumnOrder('down', index);
                                }}
                              />
                            </Tooltip>
                          </Row>
                          <Row>
                            <Col span={12}>
                              <ProFormText
                                {...columnLayout12}
                                rules={[
                                  {
                                    required: true,
                                  },
                                ]}
                                label="列名"
                                name="dataIndex"
                              />
                            </Col>
                            <Col span={12}>
                              <ProFormText
                                {...columnLayout12}
                                rules={[
                                  {
                                    required: true,
                                  },
                                ]}
                                name="title"
                                label="标题"
                              />
                            </Col>
                            <Col span={12}>
                              <ProFormSelect
                                {...columnLayout12}
                                label="值类型"
                                name="valueType"
                                options={valueTypeArray.map((valueType) => ({
                                  label: valueType.label,
                                  value: valueType.value,
                                }))}
                              />
                            </Col>
                            <Col span={12}>
                              <ProFormText {...columnLayout12} label="列提示" name="tooltip" />
                            </Col>
                            <Col span={12}>
                              <ProFormText {...columnLayout12} label="查询顺序" name="order" />
                            </Col>
                            <Col span={12}>
                              <ProFormSelect
                                {...columnLayout12}
                                name="fixed"
                                label="固定列"
                                options={[
                                  {
                                    label: 'Left',
                                    value: 'left',
                                  },
                                  {
                                    label: 'right',
                                    value: 'right',
                                  },
                                ]}
                              />
                            </Col>
                          </Row>
                          <Row>
                            <Col span={8}>
                              <ProFormSwitch
                                {...columnLayout8}
                                label="主键"
                                name="key"
                                fieldProps={{
                                  onChange: (open: boolean, event: any) => {
                                    // console.debug("设置表格rowKey", open, event, meta, config.columns[index].dataIndex)
                                    if (open) {
                                      const dataIndex = config.tableConfig.columns[index].dataIndex;
                                      setRowKey(dataIndex);
                                    } else {
                                      setRowKey('');
                                    }
                                  },
                                }}
                              />
                            </Col>
                            <Col span={8}>
                              <ProFormSwitch {...columnLayout8} label="过长省略" name="ellipsis" />
                            </Col>
                            <Col span={8}>
                              <ProFormSwitch {...columnLayout8} label="复制按钮" name="copyable" />
                            </Col>
                            <Col span={8}>
                              <ProFormSwitch {...columnLayout8} label="表格中隐藏" name="hideInTable" />
                            </Col>
                            <Col span={8}>
                              <ProFormSwitch {...columnLayout8} label="筛选中隐藏" name="hideInSearch" />
                            </Col>
                            <Col span={8}>
                              <ProFormSwitch {...columnLayout8} tooltip="排序实现需要手写sorter: (a, b) => a.age - b.age," label="开启排序" name="sorter" />
                            </Col>
                          </Row>
                          <Row>
                            <ProFormDependency name={['valueType', 'valueEnum']}>
                              {({ valueType, valueEnum }) => {
                                if (valueType !== 'select') {
                                  return null;
                                }
                                return (
                                  <ProFormTextArea
                                    {...columnLayout12}
                                    formItemProps={{}}
                                    fieldProps={{
                                      value: JSON.stringify(valueEnum),
                                    }}
                                    normalize={(value) => {
                                      return JSON.parse(value);
                                    }}
                                    label="数据枚举"
                                    name="valueEnum"
                                  />
                                );
                              }}
                            </ProFormDependency>
                          </Row>
                        </div>
                      );
                    }}
                  </ProFormList>
                </ProForm>
              </div>
            ),
          },
          {
            label: '数据源',
            key: 'dataSource',
            forceRender: true,
            children: (
              <div className="tabChildren">
                <ProForm
                  layout="horizontal"
                  labelAlign="left"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 16 }}
                  size={configSettingUI.size}
                  formRef={dataSourceFormRef}
                  submitter={false}
                  // initialValues={config}
                  onFinish={async (values) => {
                    // console.debug(values);
                    return true;
                  }}
                  onValuesChange={(_, values) => updateConfig.run(values)}
                >
                  <ProFormText
                    name={['dataSource', 'keyInfo', 'key']}
                    label="主键Key"
                    tooltip="数据唯一键"
                    placeholder="请输入主键Key"
                    rules={[
                      {
                        required: true,
                        message: '请输入主键Key',
                      },
                    ]}
                  />
                  {/* <ProFormText
                    name={['dataSource', 'keyInfo', 'value']}
                    label="主键Value"
                    tooltip="数据唯一键的有效值"
                    placeholder="请输入主键Value"
                    rules={[
                      {
                        required: true,
                        message: '请输入主键Value',
                      },
                    ]}
                  /> */}
                  <ProFormText
                    name={['dataSource', 'paginationInfo', 'currentField']}
                    label="页码字段"
                    tooltip="页码字段"
                    placeholder="请输入页码字段"
                    rules={[
                      {
                        required: true,
                        message: '请输入页码字段',
                      },
                    ]}
                  />
                  <ProFormText
                    name={['dataSource', 'paginationInfo', 'pageSizeField']}
                    label="页容字段"
                    tooltip="页容字段"
                    placeholder="请输入页容字段"
                    rules={[
                      {
                        required: true,
                        message: '请输入页容字段',
                      },
                    ]}
                  />
                  <ProFormGroup title="查-列表" collapsible defaultCollapsed={true} direction="vertical" labelLayout="twoLine">
                    <Row className="data-source-row">
                      <Col span={24}>
                        <ProFormText
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'list', 'url']}
                          label="URL地址"
                          tooltip="URL地址"
                          placeholder="请输入URL"
                          rules={[
                            {
                              required: true,
                              message: '请输入URL',
                            },
                          ]}
                        />
                      </Col>
                      <Col span={24}>
                        <ProFormRadio.Group
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'list', 'method']}
                          tooltip="请求方式"
                          label="请求方式"
                          radioType="button"
                          valueEnum={{
                            Get: 'GET',
                            Post: 'POST',
                            Put: 'PUT',
                            Delete: 'DELETE',
                          }}
                          rules={[
                            {
                              required: true,
                              message: '请选择请求方式！',
                            },
                          ]}
                        />
                      </Col>
                      <Col span={24}>
                        <ProFormTextArea {...dataSourceLayout24} name={['dataSource', 'apiList', 'list', 'body']} label="请求体" tooltip="请求体" placeholder="请输入请求体" />
                      </Col>
                      <Col span={24}>
                        <ProFormTextArea
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'list', 'afterScript']}
                          label="后执行脚本"
                          tooltip="解析返回的数据,response为响应数据,data代表解析到的数据,total代表总条数"
                          placeholder="请输入后执行脚本"
                        />
                      </Col>
                      <Col span={12}>
                        <ProFormItem {...dataSourceLayout24}>
                          <Button type="primary" onClick={() => exetDataSource('list')}>
                            执行
                          </Button>
                        </ProFormItem>
                      </Col>
                    </Row>
                  </ProFormGroup>
                  <ProFormGroup title="查-详情" collapsible defaultCollapsed={true} direction="horizontal" labelLayout="twoLine">
                    <Row className="data-source-row">
                      <Col span={24}>
                        <ProFormText
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'detail', 'url']}
                          label="URL地址"
                          tooltip="URL地址"
                          placeholder="请输入URL"
                          rules={[
                            {
                              required: true,
                              message: '请输入URL',
                            },
                          ]}
                        />
                      </Col>
                      <Col span={24}>
                        <ProFormRadio.Group
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'detail', 'method']}
                          tooltip="请求方式"
                          label="请求方式"
                          radioType="button"
                          valueEnum={{
                            GET: 'GET',
                            POST: 'POST',
                            Put: 'PUT',
                            Delete: 'DELETE',
                          }}
                          rules={[
                            {
                              required: true,
                              message: '请选择请求方式！',
                            },
                          ]}
                        />
                      </Col>
                      <Col span={24}>
                        <ProFormTextArea
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'detail', 'afterScript']}
                          label="后执行脚本"
                          tooltip="解析返回的数据,response为响应数据,data代表解析到的数据,total代表总条数"
                          placeholder="请输入后执行脚本"
                        />
                      </Col>
                      <Col span={24}>
                        <ProFormItem {...dataSourceLayout24}>
                          <Button type="primary" onClick={() => exetDataSource('detail')}>
                            执行
                          </Button>
                        </ProFormItem>
                      </Col>
                    </Row>
                  </ProFormGroup>
                  <ProForm.Group title="增" collapsible defaultCollapsed={true} direction="horizontal" labelLayout="twoLine">
                    <Row className="data-source-row">
                      <Col span={24}>
                        <ProFormText
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'add', 'url']}
                          label="URL地址"
                          tooltip="URL地址"
                          placeholder="请输入URL"
                          rules={[
                            {
                              required: true,
                              message: '请输入URL',
                            },
                          ]}
                        />
                      </Col>
                      <Col span={24}>
                        <ProFormRadio.Group
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'add', 'method']}
                          tooltip="请求方式"
                          label="请求方式"
                          radioType="button"
                          valueEnum={{
                            GET: 'GET',
                            POST: 'POST',
                            Put: 'PUT',
                            Delete: 'DELETE',
                          }}
                          rules={[
                            {
                              required: true,
                              message: '请选择请求方式！',
                            },
                          ]}
                        />
                      </Col>
                      <Col span={24}>
                        <ProFormTextArea
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'add', 'afterScript']}
                          label="后执行脚本"
                          tooltip="解析返回的数据,response为响应数据,data代表解析到的数据,total代表总条数"
                          placeholder="请输入后执行脚本"
                        />
                      </Col>
                    </Row>
                  </ProForm.Group>
                  <ProForm.Group title="改" collapsible defaultCollapsed={true} direction="horizontal" labelLayout="twoLine">
                    <Row className="data-source-row">
                      <Col span={24}>
                        <ProFormText
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'update', 'url']}
                          label="URL地址"
                          tooltip="URL地址"
                          placeholder="请输入URL"
                          rules={[
                            {
                              required: true,
                              message: '请输入URL',
                            },
                          ]}
                        />
                      </Col>
                      <Col span={24}>
                        <ProFormRadio.Group
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'update', 'method']}
                          tooltip="请求方式"
                          label="请求方式"
                          radioType="button"
                          valueEnum={{
                            GET: 'GET',
                            POST: 'POST',
                            Put: 'PUT',
                            Delete: 'DELETE',
                          }}
                          rules={[
                            {
                              required: true,
                              message: '请选择请求方式！',
                            },
                          ]}
                        />
                      </Col>
                      <Col span={24}>
                        <ProFormTextArea
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'update', 'afterScript']}
                          label="后执行脚本"
                          tooltip="解析返回的数据,response为响应数据,data代表解析到的数据,total代表总条数"
                          placeholder="请输入后执行脚本"
                        />
                      </Col>
                    </Row>
                  </ProForm.Group>
                  <ProForm.Group title="删" collapsible defaultCollapsed={true} direction="horizontal" labelLayout="twoLine">
                    <Row className="data-source-row">
                      <Col span={24}>
                        <ProFormText
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'delete', 'url']}
                          label="URL地址"
                          tooltip="URL地址"
                          placeholder="请输入URL"
                          rules={[
                            {
                              required: true,
                              message: '请输入URL',
                            },
                          ]}
                        />
                      </Col>
                      <Col span={24}>
                        <ProFormRadio.Group
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'delete', 'method']}
                          tooltip="请求方式"
                          label="请求方式"
                          radioType="button"
                          valueEnum={{
                            GET: 'GET',
                            POST: 'POST',
                            Put: 'PUT',
                            Delete: 'DELETE',
                          }}
                          rules={[
                            {
                              required: true,
                              message: '请选择请求方式！',
                            },
                          ]}
                        />
                      </Col>
                      <Col span={24}>
                        <ProFormTextArea
                          {...dataSourceLayout24}
                          name={['dataSource', 'apiList', 'delete', 'afterScript']}
                          label="后执行脚本"
                          tooltip="解析返回的数据,response为响应数据,data代表解析到的数据,total代表总条数"
                          placeholder="请输入后执行脚本"
                        />
                      </Col>
                    </Row>
                  </ProForm.Group>
                </ProForm>
              </div>
            ),
          },
          {
            label: '代码生成',
            key: 'generate',
            forceRender: true,
            children: (
              <div className="tabChildren">
                <ProForm
                  layout="horizontal"
                  labelAlign="left"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                  formRef={generateFormRef}
                  size={configSettingUI.size}
                  colon={false}
                  submitter={{
                    render: (props, doms) => {
                      return [
                        ...doms,
                        <Button htmlType="button" onClick={fillGenerate} key="edit">
                          一键填写
                        </Button>,
                      ];
                    },
                  }}
                  onFinish={async (values) => {
                    // console.debug('generateFormRef:', values);
                    generate(values);
                    // message.success('提交成功');
                    return true;
                  }}
                >
                  <ProFormText name="previewUrl" label="预览地址" tooltip="预览地址" placeholder="请输入预览地址" />
                  <ProFormText
                    name="name"
                    label="组件名"
                    tooltip="组件名"
                    placeholder="请输入组件名"
                    rules={[
                      {
                        required: true,
                        message: '请输入组件名',
                      },
                    ]}
                  />
                  {/* <ProFormSelect
                      fieldProps={{
                        size: config.selectSize,
                      }}
                      name="type"
                      tooltip="类型"
                      label="类型"
                      valueEnum={{
                        CommonTable: '普通表格',
                      }}
                      placeholder="请选择类型"
                      rules={[
                        {
                          required: true,
                          message: '请选择类型！',
                        },
                      ]}
                    /> */}
                  <ProFormText
                    name="templatePath"
                    label="模板路径"
                    tooltip="模板路径"
                    placeholder="请输入模板路径"
                    rules={[
                      {
                        required: true,
                        message: '请输入模板路径',
                      },
                    ]}
                  />
                  <ProFormText
                    name="generatePath"
                    label="生成路径"
                    tooltip="生成路径"
                    placeholder="请输入生成路径"
                    rules={[
                      {
                        required: true,
                        message: '请输入生成路径',
                      },
                    ]}
                  />
                  {/* <ProFormTextArea
                    name="initData"
                    label="初始配置"
                    tooltip="初始配置"
                    placeholder="请输入初始配置"
                    rules={[
                      {
                        required: true,
                        message: '请输入初始配置',
                      },
                    ]}
                  /> */}
                  {/* <ProFormTextArea
                    name="columns"
                    label="列配置"
                    tooltip="初始列配置"
                    placeholder="请输入列配置"
                    rules={[
                      {
                        required: true,
                        message: '请输入列配置',
                      },
                    ]}
                  /> */}
                  {/* <ProFormTextArea
                    name="tableDataList"
                    label="表格数据"
                    tooltip="表格数据"
                    placeholder="请输入表格数据"
                    rules={[
                      {
                        required: true,
                        message: '请输入表格数据',
                      },
                    ]}
                  /> */}
                </ProForm>
              </div>
            ),
          },
          {
            label: '本地缓存',
            key: 'localStorage',
            forceRender: true,
            children: (
              <div className="tabChildren">
                <ProForm
                  layout="inline"
                  size={configSettingUI.size}
                  formRef={localStorageFormRef}
                  submitter={false}
                  colon={false}
                  onValuesChange={(_, values) => updateLocalStorageConfig.run(values)}
                >
                  <ProFormList<SchemeItemInfo>
                    name="schemeList"
                    style={{ width: '100%' }}
                    actionRef={columnFormListRef}
                    creatorButtonProps={false}
                    itemRender={({ listDom, action }) => {
                      return (
                        <ProCard
                          className="datasource-form-list-card"
                          bordered
                          style={{
                            marginBlockEnd: 8,
                            position: 'relative',
                            padding: '10px 0px',
                          }}
                          bodyStyle={{
                            width: '100%',
                            padding: 8,
                            paddingBlockStart: 16,
                          }}
                        >
                          {listDom}
                        </ProCard>
                      );
                    }}
                  >
                    {(
                      // 当前行的基本信息 {name: number; key: number}
                      meta,
                      // 当前的行号
                      index,
                      /**
                       * action
                       * @name 用于操作行的一些快捷方法
                       * @example 给第二行增加数据 action.add?.({},1);
                       * @example 删除第二行 action.remove?.(1);
                       * @example 从 1 移到 2: action.move?.(2,1);
                       * @example 获取当前行的数据: action.getCurrentRowData() -> {id:"xxx",name:'123',age:18}
                       * @example 设置当前行的数据: {id:"123",name:'123'} -> action.setCurrentRowData({name:'xxx'}) -> {id:"123",name:'xxx'}
                       * @example 清空当前行的数据：{id:"123",name:'123'} -> action.setCurrentRowData({name:undefined}) -> {id:"123"}
                       */
                      action,
                      // 总行数
                      count,
                    ) => {
                      return (
                        <div key={'row_' + index}>
                          <Row>
                            <Col span={24}>
                              <ProFormText name="key" label="key" tooltip="key" readonly={true} />
                            </Col>
                          </Row>
                          <ProFormText name="title" label="方案名" tooltip="方案名" placeholder="请输入方案名" />
                          <ProFormText name="data" label="方案配置" tooltip="方案配置" placeholder="请输入方案配置" />
                          <ProFormItem>
                            <Button
                              onClick={() => {
                                loadSchemeInfo(index);
                              }}
                            >
                              使用此方案
                            </Button>
                          </ProFormItem>
                          <ProFormItem>
                            <Button
                              type="primary"
                              onClick={() => {
                                removeSchemeInfo(index);
                              }}
                            >
                              删除
                            </Button>
                          </ProFormItem>
                        </div>
                      );
                    }}
                  </ProFormList>
                  <Button
                    type="primary"
                    onClick={() => {
                      console.debug(proTableContexteValue);
                      reloadSchemeInfo();
                    }}
                  >
                    重新加载
                  </Button>
                  <Button
                    type="primary"
                    onClick={() => {
                      saveSchemeInfo();
                    }}
                  >
                    保存当前方案
                  </Button>
                  <Button
                    type="primary"
                    onClick={() => {
                      let a = config.tableConfig.columns[6].render;
                      console.debug(a, a.toString());
                    }}
                  >
                    打印函数
                  </Button>
                </ProForm>
              </div>
            ),
          },
        ]}
      ></Tabs>
    </>
  );
};
ProTableDynamicSettings.propTypes = {
  dynamicSetConfig: PropTypes.func,
  onSettingEvent: PropTypes.func,
  onEventTabelType: PropTypes.func,
};

export default React.memo(ProTableDynamicSettings);
